"""会话管理API路由：处理会话的创建、查询、修改"""
from fastapi import APIRouter, HTTPException
from typing import List
from models.request import CreateSessionRequest
from models.response import SessionResponse, ApiResponse  # 导入ApiResponse
from db.chat_session import (
    create_chat_session,
    get_user_sessions,
    get_session_by_id,
    update_session_title
)

# 创建路由实例
session_router = APIRouter(prefix="/chat-api/chat/sessions", tags=["会话管理"])

@session_router.post("")
async def create_session(request: CreateSessionRequest) -> ApiResponse[SessionResponse]:
    """创建新对话会话"""
    session = create_chat_session(
        user_id=request.user_id,
        title=request.title
    )
    # 包装成统一响应格式
    return ApiResponse(
        data=SessionResponse(**session),
        msg="会话创建成功"
    )

@session_router.get("")
async def get_sessions(user_id: str) -> ApiResponse[List[SessionResponse]]:
    """获取用户的所有对话会话"""
    sessions = get_user_sessions(user_id=user_id)
    return ApiResponse(
        data=[SessionResponse(** session) for session in sessions],
        msg="会话列表获取成功"
    )

@session_router.get("/{session_id}")
async def get_session_detail(session_id: str, user_id: str) -> ApiResponse[SessionResponse]:
    """获取单个会话的详细信息"""
    session = get_session_by_id(session_id=session_id, user_id=user_id)
    if not session:
        raise HTTPException(status_code=404, detail="会话不存在或无权限访问")
    return ApiResponse(
        data=SessionResponse(**session),
        msg="会话详情获取成功"
    )

@session_router.patch("/{session_id}/title")
async def modify_session_title(
    session_id: str,
    user_id: str,
    title: str
) -> ApiResponse[bool]:
    """修改会话标题"""
    success = update_session_title(
        session_id=session_id,
        user_id=user_id,
        title=title
    )
    if not success:
        raise HTTPException(status_code=404, detail="会话不存在或无权限修改")
    return ApiResponse(
        data=success,
        msg="会话标题修改成功"
    )
